/**
 * 
 */
package name.pathfinder.tuberose.example.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.util.finder.ClassLoaderInterface;

/**
 * @author yaowei
 *
 */
public class OsgiClassLoader implements ClassLoaderInterface {
	
	private Bundle currentBundle;
	private static final Logger logger = LoggerFactory.getLogger(OsgiClassLoader.class);

	public OsgiClassLoader(Bundle currentBundle) {
		this.currentBundle = currentBundle;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.util.finder.ClassLoaderInterface#loadClass(java.lang.String)
	 */
	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		logger.debug("loadClass: {}", name);
		return currentBundle.loadClass(name);
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.util.finder.ClassLoaderInterface#getResource(java.lang.String)
	 */
	@Override
	public URL getResource(String name) {
		logger.debug("getResource: {}", name);
		return currentBundle.getResource(name);
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.util.finder.ClassLoaderInterface#getResources(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Enumeration<URL> getResources(String name) throws IOException {
		logger.debug("getResources: {}", name);
		if(null == name) throw new IllegalArgumentException("name can not be null.");
		Vector<URL> resources = new Vector<URL>();
		
		if(name.length() == 0) { // call getResources("")
			Enumeration entries1 = currentBundle.findEntries("/", "*.jar", true);
			logger.debug("{}", entries1);
			
			Enumeration entries2 = currentBundle.getEntryPaths("/");
			logger.debug("{}", entries2);
			
		}
		Enumeration<URL> result = currentBundle.getResources(name);
		if(null != result) resources.addAll(Collections.list(result));
		return resources.elements();
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.util.finder.ClassLoaderInterface#getResourceAsStream(java.lang.String)
	 */
	@Override
	public InputStream getResourceAsStream(String name) throws IOException {
		logger.debug("getResourceAsStream: {}", name);
		URL resource = getResource(name);
		if(null != resource) return resource.openStream();
		return null;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.util.finder.ClassLoaderInterface#getParent()
	 */
	@Override
	public ClassLoaderInterface getParent() {
		return null;
	}

}
